/**
 * 
 */
package com.wubo.sec.web.action;


import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.wubo.sec.core.UserLoginPageHelper;
import com.wubo.sec.log.LogHelper;
/**
 * 
 * @author WuBo
 * @CreateDate 2012-2-20
 */
@Component("exceptionHandler")
@Scope(value="singleton")
public class DefaultExceptionHandler {
	private static final Log logger  = LogFactory.getLog(DefaultExceptionHandler.class);
	
	private static final String ERROR = "error";

	public String execute(){
		Object ex = ActionContext.getContext().getValueStack()
		.findValue("exception");
		if(ex != null){
			Exception e = (Exception) ex;

			logger.error(e.getMessage(), e);
			
			try{
				if(! checkExceptionType(e)){
					return null;
				}
			}catch(Exception err){
				logger.warn("Exception On checkExceptionType: "+err.getMessage());
			}
			
			LogHelper.errorLog(e);
		}
		//判断是否是脚本请求，脚本请求不应该转向错误页面，而由Action自己决定返回内容
		HttpServletRequest request = ServletActionContext.getRequest();
		if(request != null){
			if(UserLoginPageHelper.isScriptRequest(request)){
				return null;
			}
		}
		return ERROR;
	}
	
	protected boolean checkExceptionType(Exception e) throws IOException {
		if(e instanceof AccessDeniedException){
			ServletActionContext.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
			return false;
		}
		return true;
	}
}
